﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace OmniKits.Windows.Behaviors
{
    public class CaptureMouseBehavior
        : Behavior<UIElement>
    {
        UIElement _Element;

        protected override void OnAttached()
        {
            _Element = this.AssociatedObject;

            _Element.PreviewMouseDown += MouseDown;
            _Element.PreviewMouseUp += MouseUp;
        }

        protected override void OnDetaching()
        {
            _Element.PreviewMouseDown -= MouseDown;
            _Element.PreviewMouseUp -= MouseUp;

            _Element = null;
        }

        private bool _Middle;
        private bool _Left;
        private bool _Right;
        private bool _X1;
        private bool _X2;
        private void MouseDown(object sender, MouseButtonEventArgs e)
        {
            switch (e.ChangedButton)
            {
                case MouseButton.Left:
                    _Left = true;
                    break;
                case MouseButton.Right:
                    _Right = true;
                    break;
                case MouseButton.Middle:
                    _Middle = true;
                    break;
                case MouseButton.XButton1:
                    _X1 = true;
                    break;
                case MouseButton.XButton2:
                    _X2 = true;
                    break;
            }

            Debug.WriteLine("CaptureMouseBehavior::MouseDown");

            if (Mouse.Captured == null)
                Mouse.Capture(_Element);
        }

        private void MouseUp(object sender, MouseButtonEventArgs e)
        {
            switch (e.ChangedButton)
            {
                case MouseButton.Left:
                    _Left = false;
                    break;
                case MouseButton.Right:
                    _Right = false;
                    break;
                case MouseButton.Middle:
                    _Middle = false;
                    break;
                case MouseButton.XButton1:
                    _X1 = false;
                    break;
                case MouseButton.XButton2:
                    _X2 = false;
                    break;
            }

            if (Mouse.Captured == _Element && !(_Left || _Right || _Middle || _X1 || _X2))
                Mouse.Capture(null);
        }
    }
}
